Custom hooks are used to encapsulate and reuse stateful logic across multiple components. To create a custom hook, follow these steps:
Start with 'use': prefix the Name of the custom hook with 'use' to make it clear that it's a hook.
Reuse Existing Hooks: Custom hooks can internally use built-in hooks to achieve functionality.
Change the document title based on rendered values
Get or set values from local storage
Run analytics events
Show some greetings based on the time of day
Focus on a form field after the load
Imagine you need to fetch data in two different components and keep the loading and error handling logic consistent. How would you use a custom hook to solve this?
You have a component that needs to subscribe to a window resize event and clean it up on unmount. Walk me through how you'd implement that with a custom hook.
We have a form component that uses several pieces of state and validation logic, and another component that needs the same validation. If the validation started failing after a recent refactor, how would you debug the custom hook handling it?
Suppose you need to share a WebSocket connection across multiple components, but you also need to ensure only one connection is opened. How would you design a custom hook for this, and what trade‑offs would you consider?
Our dashboard renders dozens of widgets, each using a custom hook that polls an API every few seconds. At scale, we notice performance degradation. How would you redesign the hook or its usage to mitigate the impact?
A legacy codebase has many duplicated useEffect blocks for handling authentication token refresh. You propose extracting them into a custom hook. What concerns would you raise about testing, dependency arrays, and future extensibility?
The company is moving from a monorepo of multiple React apps to a shared component library. How would you establish guidelines for creating custom hooks to ensure consistency, avoid hidden side effects, and support cross‑team ownership?
We need to migrate a large set of class components that use lifecycle methods into functional components with hooks. What strategy would you use for converting complex lifecycle logic into custom hooks, and how would you manage the rollout without breaking existing features?